import React, { useState, useEffect, useRef, useCallback } from 'react';
import { 
  Dialog, 
  DialogTitle, 
  DialogContent, 
  Box, 
  Typography, 
  TextField, 
  Button, 
  Avatar, 
  CircularProgress, 
  IconButton,
  Divider
} from '@mui/material';
import { Send as SendIcon, Close as CloseIcon } from '@mui/icons-material';
import { useMessages } from '../MessagesContext';
import { useAuth } from '../../auth/AuthContext';
import { MessageService } from '../services/MessageService';

interface MessagePopupProps {
  open: boolean;
  onClose: () => void;
  userId: string;
  userName: string;
}

const MessagePopup: React.FC<MessagePopupProps> = ({ open, onClose, userId, userName }) => {
  const [message, setMessage] = useState('');
  const [conversation, setConversation] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const { messages, sendMessage, markAsRead } = useMessages();
  const { user } = useAuth();
  const messagesEndRef = useRef<HTMLDivElement>(null);
  
  // 使用useCallback优化加载对话的函数
  const loadConversation = useCallback(async () => {
    if (!user || !userId || !open) return;
    
    try {
      setLoading(true);
      // 获取对话内容
      const conversationData = await MessageService.getConversation(userId);
      setConversation(conversationData);
      
      // 标记消息为已读
      const unreadMessages = messages.filter(
        msg => msg.senderId === userId && msg.receiverId === user.id && !msg.isRead
      );
      
      if (unreadMessages.length > 0) {
        await MessageService.markMessagesAsRead(userId);
      }
      
      // 滚动到最新消息
      scrollToBottom();
    } catch (error) {
      console.error('加载对话失败:', error);
    } finally {
      setLoading(false);
    }
  }, [userId, messages, user, open]);
  
  // 当userId或open状态变化时加载对话
  useEffect(() => {
    if (open) {
      loadConversation();
    }
  }, [loadConversation, open]);

  // 自定义关闭处理函数，清空输入框
  const handleClose = () => {
    setMessage(''); // 清空输入框
    onClose();
  };
  
  const scrollToBottom = () => {
    setTimeout(() => {
      messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    }, 100);
  };
  
  const handleSendMessage = async () => {
    if (!message.trim() || !userId || !user) return;
    
    try {
      setLoading(true);
      const sentMessage = await sendMessage({
        receiverId: userId,
        content: message.trim(),
      });
      
      // 清空输入框
      setMessage('');
      
      // 更新对话列表
      setConversation(prev => [...prev, sentMessage]);
      
      // 滚动到最新消息
      scrollToBottom();
    } catch (error) {
      console.error('发送消息失败:', error);
    } finally {
      setLoading(false);
    }
  };
  
  const formatTime = (timestamp: string) => {
    try {
      // 处理数据库格式的时间戳 (YYYY-MM-DD HH:MM:SS)
      if (!timestamp) return '时间未知';
      
      // 如果是数据库格式的时间戳，直接提取时间部分
      if (timestamp.includes(' ')) {
        return timestamp.split(' ')[1] || '时间未知';
      }
      
      // 尝试解析为Date对象
      const date = new Date(timestamp);
      if (isNaN(date.getTime())) {
        return '时间未知';
      }
      
      return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    } catch (error) {
      console.error('格式化时间错误:', error, timestamp);
      return '时间未知';
    }
  };
  
  const formatDate = (timestamp: string) => {
    try {
      // 处理数据库格式的时间戳 (YYYY-MM-DD HH:MM:SS)
      if (!timestamp) return '日期未知';
      
      // 如果是数据库格式的时间戳，直接提取日期部分
      if (timestamp.includes(' ')) {
        return timestamp.split(' ')[0] || '日期未知';
      }
      
      // 尝试解析为Date对象
      const date = new Date(timestamp);
      if (isNaN(date.getTime())) {
        return '日期未知';
      }
      
      return date.toLocaleDateString([], { year: 'numeric', month: 'long', day: 'numeric' });
    } catch (error) {
      console.error('格式化日期错误:', error, timestamp);
      return '日期未知';
    }
  };
  
  // 判断是否显示日期（如果与前一条消息日期不同）
  const showDate = (index: number, timestamp: string) => {
    try {
      if (index === 0) return true;
      if (!timestamp || !conversation[index - 1].timestamp) return true;
      
      // 如果是数据库格式的时间戳，直接提取日期部分比较
      if (timestamp.includes(' ') && conversation[index - 1].timestamp.includes(' ')) {
        const currentDate = timestamp.split(' ')[0];
        const prevDate = conversation[index - 1].timestamp.split(' ')[0];
        return currentDate !== prevDate;
      }
      
      // 尝试解析为Date对象比较
      const currentDate = new Date(timestamp);
      const prevDate = new Date(conversation[index - 1].timestamp);
      
      // 检查日期是否有效
      if (isNaN(currentDate.getTime()) || isNaN(prevDate.getTime())) {
        return true; // 如果任一日期无效，默认显示日期
      }
      
      return (
        currentDate.getFullYear() !== prevDate.getFullYear() ||
        currentDate.getMonth() !== prevDate.getMonth() ||
        currentDate.getDate() !== prevDate.getDate()
      );
    } catch (error) {
      console.error('比较日期错误:', error, timestamp);
      return true; // 出错时默认显示日期
    }
  };

  return (
    <Dialog 
      open={open} 
      onClose={handleClose} 
      maxWidth="sm" 
      fullWidth 
      PaperProps={{
        sx: { 
          height: '80vh',
          display: 'flex',
          flexDirection: 'column'
        }
      }}
    >
      <DialogTitle sx={{ p: 2, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <Box sx={{ display: 'flex', alignItems: 'center' }}>
          <Avatar sx={{ mr: 2 }}>{userName.charAt(0).toUpperCase()}</Avatar>
          <Typography variant="h6">{userName}</Typography>
        </Box>
        <IconButton onClick={handleClose} size="small">
          <CloseIcon />
        </IconButton>
      </DialogTitle>
      <Divider />
      
      <DialogContent sx={{ flexGrow: 1, overflow: 'auto', p: 2, display: 'flex', flexDirection: 'column' }}>
        {loading && conversation.length === 0 && (
          <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%' }}>
            <CircularProgress />
          </Box>
        )}
        {!loading && conversation.length === 0 && (
          <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%' }}>
            <Typography variant="body1" color="text.secondary">
              暂无消息，开始聊天吧
            </Typography>
          </Box>
        )}
        {conversation.length > 0 && (
          <Box>
            {conversation.map((msg, index) => {
              const isCurrentUser = msg.senderId === user?.id;
              
              // 添加日期有效性检查
              const isCurrentDateValid = msg.timestamp && !isNaN(new Date(msg.timestamp).getTime());
              const isPrevDateValid = index > 0 && conversation[index - 1].timestamp && 
                !isNaN(new Date(conversation[index - 1].timestamp).getTime());
              
              // 判断是否显示日期
              const showDate = index === 0 || 
                !isPrevDateValid || 
                !isCurrentDateValid || 
                (isCurrentDateValid && isPrevDateValid && 
                  new Date(msg.timestamp).toDateString() !== 
                  new Date(conversation[index - 1].timestamp).toDateString());
              
              return (
                <Box key={msg.id ? `msg-${msg.id}` : `msg-index-${index}`}>
                  {showDate && (
                    <Box sx={{ textAlign: 'center', my: 2 }}>
                      <Typography variant="caption" color="text.secondary">
                        {formatDate(msg.timestamp)}
                      </Typography>
                    </Box>
                  )}
                  <Box
                    sx={{
                      display: 'flex',
                      justifyContent: isCurrentUser ? 'flex-end' : 'flex-start',
                      mb: 2,
                    }}
                  >
                    {!isCurrentUser && (
                      <Avatar sx={{ mr: 1, width: 32, height: 32 }}>
                        {userName.charAt(0).toUpperCase()}
                      </Avatar>
                    )}
                    <Box
                      sx={{
                        maxWidth: '70%',
                        p: 1.5,
                        borderRadius: 2,
                        bgcolor: isCurrentUser ? 'primary.main' : 'grey.100',
                        color: isCurrentUser ? 'white' : 'text.primary',
                      }}
                    >
                      <Typography variant="body1">{msg.content}</Typography>
                      <Typography
                        variant="caption"
                        sx={{
                          display: 'block',
                          textAlign: 'right',
                          mt: 0.5,
                          color: isCurrentUser ? 'rgba(255, 255, 255, 0.7)' : 'text.secondary',
                        }}
                      >
                        {formatTime(msg.timestamp)}
                      </Typography>
                    </Box>
                    {isCurrentUser && (
                      <Avatar sx={{ ml: 1, width: 32, height: 32 }}>
                        {user?.username?.charAt(0).toUpperCase() || 'U'}
                      </Avatar>
                    )}
                  </Box>
                </Box>
              );
            })}
            <div ref={messagesEndRef} />
          </Box>
        )}
      </DialogContent>
      
      <Divider />
      <Box sx={{ p: 2, borderTop: 1, borderColor: 'divider' }}>
        <Box sx={{ display: 'flex' }}>
          <TextField
            fullWidth
            variant="outlined"
            placeholder="输入消息..."
            value={message}
            onChange={(e) => setMessage(e.target.value)}
            onKeyPress={(e) => e.key === 'Enter' && !e.shiftKey && handleSendMessage()}
            disabled={loading}
            size="small"
            sx={{ mr: 1 }}
          />
          <Button
            variant="contained"
            color="primary"
            onClick={handleSendMessage}
            disabled={!message.trim() || loading}
            sx={{
              minWidth: '80px',
              height: '40px',
              borderRadius: '4px',
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center'
            }}
          >
            发送
            <SendIcon sx={{ fontSize: '0.8rem', ml: 0.5 }} />
          </Button>
        </Box>
      </Box>
    </Dialog>
  );
};

export default MessagePopup;